package org.example.listener;

import lombok.extern.slf4j.Slf4j;
import org.example.function.Tool;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.util.Timer;
import java.util.TimerTask;

import static org.example.frame.MainFrame.formatText;
import static org.example.frame.MainFrame.resultLabel;

/**
 * 事件监听类
 * Author: Crane Resigned
 * Date: 2022-11-23 22:26:10
 *
 * @author Crane Resigned
 */
@Slf4j
public class GlobalKeyListener implements NativeKeyListener {

    /**
     * 事件监听器
     * Author: Crane Resigned
     * Date: 2022-11-23 22:46:59
     */
    private static final GlobalKeyListener GLOBAL_KEY_LISTENER = new GlobalKeyListener();

    /**
     * 事件监听按键常量
     * Author: Crane Resigned
     * Date: 2022-11-23 22:47:11
     */
    private static Integer eventKey = 29;

    public static Integer getEventKey() {
        return eventKey;
    }

    public static void setEventKey(Integer eventKey) {
        GlobalKeyListener.eventKey = eventKey;
    }

    public static GlobalKeyListener getGlobalKeyListener() {
        return GLOBAL_KEY_LISTENER;
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(nativeKeyEvent.getKeyCode()));
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {
        System.out.println("Key Typed: " + NativeKeyEvent.getKeyText(nativeKeyEvent.getKeyCode()));
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
        if (nativeKeyEvent.getKeyCode() == getEventKey()) {
            log.info("当前按键：" + NativeKeyEvent.getKeyText(nativeKeyEvent.getKeyCode()));
            log.info("当前时间戳格式：" + formatText.getText());
            Tool.stick(Tool.generateTime(formatText.getText()));
            resultLabel.setVisible(true);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    resultLabel.setVisible(false);
                }
            }, 2000);
        }
    }

}
